<template>
	<Content title="箱码件码绑定">
		<view class="device-details">
			<view class="content">
				<view class="main-box">
					<u-form labelPosition="left" :model="model" labelWidth="80" labelAlign="left" :rules="rules"
						ref="uForm">
						<view class="info-box">
							<view class="title">
								<text class="txt">绑定内容</text>
							</view>
							<view class="input-box">
								<u-form-item label="班次时间:" required prop="shiftTime">
									<MyDate @change="getShiftList" v-model="model.shiftTime" placeholder="请选择"></MyDate>
								</u-form-item>
							</view>
							<!-- 		<view class="input-box">
								<u-form-item label="班次:" required prop="shiftId">
									<zxz-uni-data-select v-model="model.shiftId" :localdata="shiftList"
										@change="getShiftTime"></zxz-uni-data-select>
								</u-form-item>
							</view> -->
							<template>
								<view class="input-box">
									<u-form-item label="箱码:" prop="boxCode" required @click="onFocus">
										<!-- readonly -->
										<u-input :class="['box-input', btnName == '箱码' ? 'isThis' : '']" label readonly
											v-model="model.boxCode" placeholder="请填写" @click="onFocus">
											<div slot="suffix" @click.stop="scanCode">
												<u-icon name="scan"></u-icon>
											</div>
										</u-input>
									</u-form-item>
								</view>
								<view class="input-box">
									<u-form-item label="件码:" prop="itemCodebyName" @click="onFocus1" required>
										<view style="width: 100%;display: flex;align-items: center;">
											<!-- disabled -->
											<u--textarea :class="['box-input', btnName == '件码' ? 'isThis' : '']"
												@click="onFocus1" v-model="model.itemCodebyName" @confirm="test" disabled
												placeholder="请填写" autoHeight>
											</u--textarea>

											<view @click.stop="scanCode1" style="margin-left: 20rpx;">
												<u-icon name="scan"></u-icon>
											</view>
										</view>
									</u-form-item>
								</view>
								<view class="item-code-list"
									v-if="model.itemCodebyList && model.itemCodebyList.length > 0">
									<view class="item-code-item" v-for="(item, index) in model.itemCodebyList"
										:key="index">
										<text class="item-label">件码{{ index + 1 }}:</text>
										<text class="item-value">{{ item.itemCode }}</text>
										<view class="delete-btn" @click="removeItemCode(index)">删除</view>
									</view>
								</view>
							</template>
							
							<view class="input-box">
								<u-form-item label="件码数量:">
							{{model.itemCodebyList.length}}
							</u-form-item>
							</view>

							<view class="input-box">
								<u-form-item label="提报方式:" required prop="reportingMethod">
									<uni-data-select v-model="model.reportingMethod"
										:localdata="data.cuttingPlanCode ? localdata : localdata"
										placeholder="请选择"></uni-data-select>
								</u-form-item>
							</view>
					
						<!-- 	<view class="input-box">
								<u-form-item :label="`${model.reportingMethod==='按数量'?'入库数量':'入库重量'}`"
									class="label-fwn">
									<MyNumber class="box-input" v-model="data.reportedQuantity" :decimal="2"
										:halfAdjust="false" :min="0" :max="99999999" placeholder="请输入">
									</MyNumber>
								</u-form-item>
							</view> -->
			<!-- 				<view class="input-box">
								<u-form-item label="入库仓库:" required prop="wareHouse">
									<zxz-uni-data-select v-model="model.wareHouse" :localdata="wareHouses"
										@change="changeWareHouse"></zxz-uni-data-select>
								</u-form-item>
							</view> -->
							<view class="input-box">
								<u-form-item label="条料标签:" prop="stripLabel" @click="onFocus2" required>
									<view style="width: 100%;display: flex;align-items: center;">
										<!-- disabled -->
										<u--textarea :class="['box-input', btnName == '条料标签' ? 'isThis' : '']"
											@click="onFocus2" v-model="model.stripLabel" placeholder="请扫描条料标签" disabled
											autoHeight @confirm="test2">
										</u--textarea>

										<view @click.stop="scanCode2" style="margin-left: 20rpx;">
											<u-icon name="scan"></u-icon>
										</view>
									</view>
								</u-form-item>
							</view>
							<view class="info-box">
								<view class="text-box">
									<text class="label">物料编号:</text>
									<text class="value">{{ model.materialCode || '--'  }}</text>
								</view>
								<view class="text-box">
									<text class="label">物料名称:</text>
									<text class="value">{{ model.materialName || '--'  }}</text>
								</view>
								<view class="text-box">
									<text class="label">卷号:</text>
									<text class="value">{{ model.volumeNumber || '--'  }}</text>
								</view>
								<view class="text-box">
									<text class="label">料位:</text>
									<text class="value">{{ model.materialLevel || '--' }}</text>
								</view>
							</view>
						</view>

						<view class="info-box select_user" @click="selectUser">
							<view class="text-box-l text-title">
								<text class="label">操作工</text>
								<view class="txt-box">
									<text class="txt" v-for="(item, index) in selectLists" :key="item.id">{{
                      item.name + (index < selectLists.length - 1 ? "," : "")
                    }}</text>
								</view>
							</view>
							<uni-icons class="icons" type="right" size="14" color="#999" />
						</view>

						<view class="info-box">
							<view class="title">
								<text class="txt u-line-1">添加图片（选填，最多5张）</text>
							</view>
							<view class="text-box">
								<view class="value">
									<MyUpload v-model="fileList" multiple :maxCount="5"></MyUpload>
								</view>
							</view>
						</view>
					</u-form>
				</view>
			</view>

			<view class="btn-v">
				<view class="but-box">
					<u-button class="btn" type="primary" @click="submit" :loading="loading" :disabled="loading"
						text="提交"></u-button>
				</view>
			</view>
		</view>
	</Content>
</template>

<script>
	import Content from "@/components/content/index";
	import fetch from "@/utils/fetch";
	import MyDate from "@/components/myDate";
	import MyUpload from "@/components/myUpload";
	import MyNumber from "@/components/MyNumber";
	import {
		getNotice,
		setNotice,
		getUserInfo
	} from "@/store/user.js";
	import {
		initScan,
		startScan,
		stopScan
	} from "@/utils/scan";

	export default {
		components: {
			Content,
			MyDate,
			MyUpload,
			MyNumber
		},
		data() {
			return {
				btnName: "",
				id: "",
				model: {
					mode: "正常",
					shift: "",
					shiftId: "",
					shiftTime: "",
					warehouseId: "",
					reportingMethod: "按数量",
					reportedQuantity: "",
					itemCodebyName: "",
					itemCodebyList: [],
					boxCode: "",
					numberOfPiece: 0,
					volumeNumber: "",
					rollWeight: "",
					quantityS: {},
					stripLabel: "",
					stripLabelInfo: null
				},
				isFocus: false,
				loading: false,
				wareHouses: [],
				volumeNumberList: [],
				rules: {
					mode: {
						required: true,
						message: "请选择",
						trigger: ["blur", "change"],
					},
					shift: {
						required: true,
						message: "请选择",
						trigger: ["blur", "change"],
					},
					shiftTime: {
						required: true,
						message: "请选择",
						trigger: ["blur", "change"],
					},
					reportingMethod: {
						required: true,
						message: "请选择",
						trigger: ["blur", "change"],
					},
					wareHouse: {
						required: true,
						message: "请选择",
						trigger: ["blur", "change"],
					},
					boxCode: {
						required: true,
						message: "请选择",
						trigger: ["blur", "change"],
					},
					itemCodebyList: {
						type: "array",
						required: true,
						message: "请选择",
						trigger: ["blur", "change"],
					},
					reportedQuantity: {
						type: "number",
						required: true,
						message: "请填写",
						trigger: ["blur", "change"],
					},
					stripLabel: {
						required: true,
						message: "请扫描条料标签",
						trigger: ["blur", "change"],
					}
				},
				navIndex: 0,
				type: "1",
				data: {
					cuttingPlanCode: true,
				},
				localdata: [{
						text: "按重量",
						value: "按重量",
					},
					{
						text: "按数量",
						value: "按数量",
					},
				],
				localdata1: [{
					text: "按数量",
					value: "按数量",
				}, ],
				typeList: [{
						text: "正常提报",
						value: "正常",
					},
					{
						text: "箱码绑定",
						value: "箱码",
					},
				],
				fileList: [],
				shiftList: [],
				userList: [],
				selectList: [],
				selectLists: [],
				itemCode: 0,
				itemCodeLoading: false
			};
		},
		onLoad() {
			// this.getWareHouseList();
			// this.getUserShift()
			this.model.shiftTime = this.$dayjs(new Date()).format("YYYY-MM-DD");
		},
		onHide() {
			stopScan();
		},
		onReady: function() {
			if (this.$refs.uForm) this.$refs.uForm.setRules(this.rules);
		},
		onShow: function() {
			const that = this;
			const userInfo = getUserInfo();
			const arr = [{
				empno: userInfo.empno,
				id: userInfo.userId,
				name: userInfo.realname,
			}, ];
			that.selectList = uni.getStorageSync("getSelectList") || [userInfo.userId];
			that.selectLists = uni.getStorageSync("getSelectLists") || arr;
			let obj = {};
			let obj1 = {};
			that.selectLists.map((item, index) => {
				obj[index + ""] = "";
				obj1["quantityS." + index] = {
					required: true,
					message: "请选择",
					trigger: ["blur", "change"],
				};
				obj.length = that.selectLists.length;
			});
			this.rules = Object.assign(this.rules, obj1);
			this.model.quantityS = obj;
			initScan(this.scanSuccess);
			startScan();
		},
		computed: {},
		mounted() {
			this.$watch('model.itemCodebyList', (newVal, oldVal) => {
				// 只有当列表长度变化时才更新（避免频繁更新）
				if (newVal.length !== oldVal.length) {
					this.model.itemCodebyList = newVal.filter(item => item && item.itemCode);
					this.updateItemCodeDisplay();
				}
			}, {
				deep: true
			});
		},
		methods: {
			test(e) {
				const param = {
					result: this.model.itemCodebyName
				}
				this.checkItemCodeBind(param)
			},
			test2(e) {
				this.handleStripLabelScan(this.model.stripLabel);
			},
			async scanSuccess(code) {
				const that = this;
				let res = {
					result: code,
				};

				if (this.btnName == "箱码") {
					that.model.boxCode = res.result;
					that.model.itemCodebyName = null
					that.model.itemCodebyList = []
					uni.showToast({
						title: '箱码扫描成功',
						icon: 'success',
						duration: 1000
					});
				} else if (this.btnName == "件码") {
					await this.checkItemCodeBind(res);
				} else if (this.btnName == "条料标签") {
					this.handleStripLabelScan(res.result);
				}
			},
			startsWith(str, prefix) {
				return new RegExp(`^${prefix}`).test(str);
			},
			async handleStripLabelScan(code) {
				try {
					if (this.startsWith(code, "TAG")) {
						const response = await fetch("post", "/dms/apiMethod/outboundLabelInfo", {
							serialNo: code
						});
						if (response.code === 1 && response.data) {
							this.model.stripLabel = code;
							this.model.materialCode = response.data[0].materialCode;
							this.model.volumeNumber = response.data[0].batchProp.prop_JH;
							this.model.materialName = response.data[0].materialName;
							this.model.materialLevel = "" // TAG标签不带料位
						} else {
							uni.$emit("openToast", {
								type: "error",
								title: response.message || "获取标签信息失败"
							});
						}
					} else if (this.startsWith(code, "scene_01")) {
						const tagSerial = code.replace("scene_01;", "");
						const response = await fetch("get",
							`/dms/labelPrinting/getLabelInfoBySerial?tagSerial=${tagSerial}`);
						console.log(response, 'response');
						if (response.code == 200 && response.data) {
							this.model.stripLabel = code;
							this.model.materialCode = response.data.materialCode;
							this.model.volumeNumber = response.data.volumeNumber;
							this.model.materialLevel = response.data.materialLevel;
							this.model.materialName = response.data.materialName;
						} else {
							uni.$emit("openToast", {
								type: "error",
								title: response.message || "获取标签信息失败"
							});
						}
					} else {
						uni.$emit("openToast", {
							type: "error",
							title: "不支持的标签格式"
						});
					}
				} catch (error) {
					console.error("条料标签扫码处理失败:", error);
					uni.$emit("openToast", {
						type: "error",
						title: "条料标签处理异常"
					});
				}
			},

			async checkItemCodeBind(itemCode) {
				const that = this;
				console.log(itemCode,'checkItemCodeBind');
				if (!this.model.boxCode) {
					uni.showToast({
						icon: 'none',
						title: '请先扫描箱码'
					})
					return false
				}
				console.log(this.itemCodeLoading, 'this.itemCodeLoading');
				// if (that.itemCodeLoading) return;
				that.itemCodeLoading = true;
				uni.showLoading({
					title: '件码验证中...',
					mask: true
				});

				try {
					const code = itemCode.result;
					if (!code || code == '') {
						that.itemCodeLoading = false;
						return;
						uni.showToast({
							title: '件码不能为空',
							icon: 'none',
							duration: 1500
						});
					}

					const res = await fetch("get", "/dms/boxItemCodeBinding/checkBind", {
						itemCode: code
					});

					if (res.code == 200) {
						that.addBoxData(code);
					} else {
						uni.hideLoading()
							that.itemCodeLoading = false;
						uni.showModal({
							title: '提示',
							content: res.msg,
							showCancel: false,
							success: function(res) {}
						});
					}
				} catch (error) {
					console.error("件码验证失败:", error);
					uni.hideLoading()
						that.itemCodeLoading = false;
					uni.showToast({
						title: '件码验证异常',
						icon: 'none',
						duration: 1500
					});
				} finally {
					that.itemCodeLoading = false;
					uni.hideLoading();
				}
			},

			addBoxData(code) {
				// 检查是否已存在
				if (this.model.itemCodebyList.some(item => item.itemCode === code)) {
					uni.showToast({
						title: '该件码已存在',
						icon: 'none',
						duration: 1500
					});
					return;
				}
				const now = new Date();
				const year = now.getFullYear();
				const month = String(now.getMonth() + 1).padStart(2, '0');
				const day = String(now.getDate()).padStart(2, '0');
				const hours = String(now.getHours()).padStart(2, '0');
				const minutes = String(now.getMinutes()).padStart(2, '0');
				const seconds = String(now.getSeconds()).padStart(2, '0');

				const currentTime = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
				// 添加新件码
				this.model.itemCodebyList.push({
					itemCode: code,
					scanDateTime: currentTime //当前时间
				});

				// 清空输入框
				this.model.itemCodebyName = '';
	this.itemCodeLoading = false;
				// 显示成功提示
				// uni.showToast({
				// 	title: '件码添加成功',
				// 	icon: 'success',
				// 	duration: 1000
				// });
			},

			updateItemCodeDisplay() {
				this.model.itemCodebyName = this.model.itemCodebyList
					.map((item) => item.itemCode)
					.join(",");
				this.model.numberOfPiece = this.model.itemCodebyList.length;
				this.model.reportedQuantity = this.model.itemCodebyList.length;
			},

			removeItemCode(index) {
				this.model.itemCodebyList.splice(index, 1);
				this.updateItemCodeDisplay();
			},

			scanCode() {
				const that = this;
				uni.scanCode({
					success: function(res) {
						that.model.boxCode = res.result;
						that.model.itemCodebyName = null
						that.model.itemCodebyList = []
						// 添加扫描成功反馈
						uni.showToast({
							title: '箱码扫描成功',
							icon: 'success',
							duration: 1000
						});
					},
				});
			},

			onFocus() {
				this.btnName = this.btnName === "箱码" ? "" : "箱码";
			},

			onFocus1() {
				this.btnName = this.btnName === "件码" ? "" : "件码";
			},

			onFocus2() {
				this.btnName = this.btnName === "条料标签" ? "" : "条料标签";
			},

			scanCode1() {
				const that = this;
				uni.scanCode({
					success: function(res) {
						console.log(res);
						that.checkItemCodeBind(res);
					},
				});
			},

			scanCode2() {
				const that = this;
				uni.scanCode({
					success: function(res) {
						that.handleStripLabelScan(res.result);
					},
				});
			},



			selectUser() {
				uni.navigateTo({
					url: "/pages/staging/production-reporting/operator1",
					animationType: "pop-in",
				});
			},

			getShiftTime(data) {
				this.model.shiftId = data.shiftId;
				this.model.shiftName = data.shift
			},

			changeWareHouse(data) {
				this.model.warehouseId = data.id;
			},

			getUserShift() {
				const that = this;
				fetch("get", "/dms/mobile/getMyShiftList", {}).then((res) => {
					if (res.data && res.data.length > 0) {
						this.model.shiftId = res.data[0].shiftId
						that.shiftList = res.data.map((item) => {
							return {
								...item,
								value: item.shiftId,
								text: item.factoryName + ' - ' + item.shift,
							};
						})
					} else {
						this.getShiftList()
					}
				});
			},

			getShiftList() {
				const that = this;
				fetch("POST", "/dms/productionShift/page", {
					pageNum: 1,
					pageSize: 999
				}).then((res) => {
					that.shiftList = res.data.records.map((item) => {
						return {
							...item,
							value: item.id,
							text: item.factoryName + ' - ' + item.shift,
						};
					})
				});
			},

			getWareHouseList() {
				fetch("post", "/dms/dmsBackupConfig/queryPage", {
					pageNum: 1,
					pageSize: 999999
				}).then((res) => {
					this.wareHouses = res.data.records.map((item) => ({
						...item,
						value: item.backupName,
						text: item.backupName,
					}));
				});
			},

			submit() {
				const that = this;
				this.$refs.uForm.validate().then((valid) => {
					if (valid) {
						that.$loading.open();
						const currentShift = this.shiftList.find(item => item.id === this.model.shiftId);
						const data = {
							itemCodeList: this.model.itemCodebyList,
							materialCode: this.model.materialCode,
							boxCode: this.model.boxCode,
							materialName: this.model.materialName,
							stripLabels: this.model.stripLabel,
							materialLevel: this.model.materialLevel || "",
							volumeNumber: this.model.volumeNumber || "",
							reportingMethod: this.model.reportingMethod,
							shiftDate: this.model.shiftTime,
							images: this.fileList.map(item => item.url)
						};
						this.loading = true;
						fetch("post", "/dms/boxItemCodeBinding/add", data).then((res) => {
							console.log(res, 'res了');
							this.loading = false;
							that.$loading.close();
							uni.$emit("openToast", {
								type: "success",
								title: "提交成功",
								complete() {
									uni.navigateTo({
										url: 'index'
									})
								},
							});
						}).catch((error) => {
							console.log(error, 'error了');
							this.loading = false;
							that.$loading.close();

						});
					} else {
						console.log("验证失败");
					}
				});
			},
		},
	};
</script>

<style scoped lang="scss">
	.isThis {
		border: 1px solid #f17a0a !important;
	}

	.device-details {
		height: 100%;
		overflow: auto;
		padding-bottom: 150rpx;

		.content {
			min-height: 100%;
		}

		.title {
			font-size: 32rpx;
			margin-bottom: 20rpx;
			padding: 0 40rpx 20rpx 40rpx;
			border-bottom: 1px solid #e0e0e0;
			display: flex;
			align-items: center;

			.txt {
				flex: 1;
			}

			.tag-box {
				display: flex;
				align-items: center;
			}
		}

		.content-top {
			padding: 40rpx;

			.state {
				color: #f17a0a;
				margin-bottom: 20rpx;
			}
		}

		.select_user {
			display: flex;
			font-size: 30rpx;
			justify-content: space-between;
			align-items: center;
			padding: 20rpx 40rpx;
		}

		.text-box-l {
			display: flex;
			justify-content: space-between;
			align-items: center;
			flex: 1;
			overflow: hidden;

			.label {
				min-width: 60px;
			}
		}

		.txt-box {
			overflow: auto;
			flex: 1;
			white-space: nowrap;
			max-width: 100%;
			flex-wrap: inherit;
			text-align: right;

			.txt {
				margin-right: 5px;
			}
		}

		.search-box {
			display: flex;
			justify-content: space-between;
			align-items: center;
			margin-bottom: 60rpx;

			.label {
				margin: 0 20rpx;
			}
		}
	}

	.u-textarea--disabled {
		pointer-events: none;
		user-select: none;
		background: #fff;
		border-color: #eee;
	}

	.item-code-list {
		padding: 0 40rpx;
		display: flex;
		flex-direction: column;

		.item-code-item {
			display: flex;
			align-items: center;
			padding: 20rpx 0;
			border-bottom: 1px solid #f5f5f5;

			.item-label {
				width: 150rpx;
				margin-right: 20rpx;
				flex-shrink: 0;
			}

			.item-value {
				flex: 1;
				margin-right: 20rpx;
				word-break: break-all;
			}

			.delete-btn {
				padding: 8rpx 20rpx;
				background-color: #f56c6c;
				color: white;
				border-radius: 6rpx;
				font-size: 24rpx;
				white-space: nowrap;
			}
		}
	}

	/deep/.uni-select__input-text {
		width: 400rpx !important;
	}
</style>